﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Newtonsoft.Json;
using RestSharp;

namespace AppDemo.utils
{
    class RestSharpUtil
    {
        internal static RestClient Instance(string url)
        {
            var restClient = new RestClient(url)
            {
                Timeout = 5000,
                ReadWriteTimeout = 5000
            };
            return restClient;
        }
        public static async System.Threading.Tasks.Task<string> Post(string url, Dictionary<string, string> dic)
        {
            string result = "";
            RestClient restClient = Instance(url);
            RestRequest request = new RestRequest();
            //request.AddQueryParameter("id","")  添加url的参数(AddUrlSegment)
            //request.AddHeader("Authorization","token");添加请求头参数
            // request.AddHeader("content-type", "application/x-www-form-urlencoded; charset=UTF-8");
            request.AddJsonBody(dic);
            //request.AddParameter("application/x-www-form-urlencoded; charset=UTF-8", user, ParameterType.RequestBody);
            var response = await restClient.ExecutePostTaskAsync(request);
            //var response = await restClient.ExecutePostTaskAsync<string>(request); 自动序列化
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                result = JsonConvert.DeserializeObject<string>(response.Content);

            }
            return result;
        }
        public static async System.Threading.Tasks.Task<string> Get(string url, Action<IRestResponse> callback)
        {
            string result = "";
            try
            {
                RestClient restClient = Instance(url);
                RestRequest request = new RestRequest();
                restClient.ExecuteAsync(request, resp =>
                {
                    if (resp.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        var v = resp.Content;
                        result = JsonConvert.DeserializeObject<string>(v); 
                    }
                    else
                    {

                    }
                });
            }
            catch (Exception)
            {

            } 
            return result;
        }

        public async System.Threading.Tasks.Task<byte[]> GetTwo(string url)
        {
            RestClient restClient = Instance(url);
            RestRequest request = new RestRequest();
            var response = await restClient.ExecuteGetTaskAsync(request);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var bytes = response.RawBytes;
                return bytes;
            }
            return null;

        }
    }
}